package justbot.justvideo;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.util.Set;
import java.util.UUID;

import javax.net.ssl.X509TrustManager;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

//import com.weibo.android.example.TestActivity;

import com.weibo.net.AccessToken;
import com.weibo.net.DialogError;
import com.weibo.net.Oauth2AccessToken;
import com.weibo.net.RequestToken;
import com.weibo.net.ShareActivity;
import com.weibo.net.Utility;
import com.weibo.net.Weibo;
import com.weibo.net.WeiboDialogListener;
import com.weibo.net.WeiboException;
import com.weibo.net.WeiboParameters;

public class JustVideo extends Activity {
	
	//�����ǰ-��-��-��-ֹͣ
	private Button btnForward = null;
	private Button btnBackward = null;
	private Button btnLeft = null;
	private Button btnRight = null;
	private Button btnStop = null;
	
	//��ʾ��Ϣ
	private TextView textMessage = null;
	private TextView msgHello = null;
	
	//����ģ��MAC��ַ��UUID
	private static String address = "00:11:05:20:05:34";
	static final String SPP_UUID = "00001101-0000-1000-8000-00805F9B34FB";
	
	//������ͨ�ŵ������
	private OutputStream outStream = null;
    private InputStream  inStream = null;
	
	BluetoothAdapter mAdapter = BluetoothAdapter.getDefaultAdapter();
	BluetoothSocket mSocket = null;
	public static BluetoothSocket btSocket; 
	
	
	//微博
	Weibo mWeibo = Weibo.getInstance();
	private Button mLogin;
	private TextView mToken;
	
	private String weibo_user_id = null;
	private String since_id = "0";
	private String weibo_id = "3433004502664832";

	private static final String URL_ACTIVITY_CALLBACK = "weiboandroidsdk://TimeLineActivity";
	private static final String FROM = "xweibo";
	
	// 设置appkey及appsecret，如何获取新浪微博appkey和appsecret请另外查询相关信息，此处不作介绍
	private static final String CONSUMER_KEY = "2250961727";// 替换为开发者的appkey，例如"1646212960";
	private static final String CONSUMER_SECRET = "c622f98a667ab0d97a071589144e4e5a";// 替换为开发者的appkey，例如"94098772160b6f8ffc1315374d8861f9";
	
	private String username = "15913188081";
	private String password = "fuck110";
	
	//用于定时器
	Handler han = new Handler();
	private int iLogin = 0;   
	
	@Override
    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        btnForward = (Button)findViewById(R.id.btnForward);
        btnBackward = (Button)findViewById(R.id.btnBackward);
        btnLeft = (Button)findViewById(R.id.btnLeft);
        btnRight = (Button)findViewById(R.id.btnRight);
        btnStop = (Button)findViewById(R.id.btnStop);
        
        mLogin = (Button)findViewById(R.id.btnLogin);
        
        btnForward.setOnClickListener(clkListener);
        btnBackward.setOnClickListener(clkListener);
        btnLeft.setOnClickListener(clkListener);
        btnRight.setOnClickListener(clkListener);
        btnStop.setOnClickListener(clkListener);
        
        mLogin.setOnClickListener(clkListener);
        
         
        textMessage = (TextView)findViewById(R.id.textMessage);
        msgHello = (TextView)findViewById(R.id.hello);
      
        
        if(!mAdapter.isEnabled())
    	{
        	
        	textMessage.setText("尝试打开蓝牙..");
    		//Intent enabler = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
    		//startActivityForResult(enabler,2);
        	mAdapter.enable();
    		textMessage.setText("蓝牙打开成功..");
    	}
        else
        {
        	textMessage.setText("蓝牙已打开..");
        }
        
        BluetoothDevice device = mAdapter.getRemoteDevice(address);
        msgHello.setText(device.getName()+" ");
        try {
        	textMessage.setText("尝试连接蓝牙设备："+device.getName());
           btSocket = device.createRfcommSocketToServiceRecord(UUID.fromString(SPP_UUID));
        } catch (IOException e) {
             textMessage.setText("连接蓝牙设备失败..");
        }
        mAdapter.cancelDiscovery();
        
        try
        {
        	textMessage.setText("尝试建立连接..");
        	btSocket.connect();
        	textMessage.setText("连接成功..");
        }
        catch(IOException e)
        {
        	try {
				btSocket.close();
			} catch (IOException e1) {
				e1.printStackTrace();
			}
        }
        
        //微博授权
        Weibo weibo = Weibo.getInstance();
        textMessage.setText("setupConsumerConfig");
		weibo.setupConsumerConfig(CONSUMER_KEY, CONSUMER_SECRET);

		// Oauth2.0
		// 隐式授权认证方式
		textMessage.setText("setRedirectUrl");
		weibo.setRedirectUrl("http://localhost/callback.php");// 此处回调页内容应该替换为与appkey对应的应用回调页
		// 对应的应用回调页可在开发者登陆新浪微博开发平台之后，
		// 进入我的应用--应用详情--应用信息--高级信息--授权设置--应用回调页进行设置和查看，
		// 应用回调页不可为空

		textMessage.setText("weibo.authorize");
		weibo.authorize(JustVideo.this,
				new AuthDialogListener());
				
		han.postDelayed(runnable,5000);

    }   

	Runnable runnable = new Runnable()
	{

		@Override
		public void run() {
			// TODO Auto-generated method stub
			//要做得事情就是读最新一条的微博信息
			if(1 == iLogin)
			{
				//ActionFromWeibo();
				ActionFromComments(weibo_id);
			}
			han.postDelayed(this, 5000);
			Toast.makeText(getApplicationContext(),
					"扫描微博命令..", Toast.LENGTH_LONG).show();
		}
		
	};
	
    private OnClickListener clkListener = new OnClickListener()
    {

		@Override
		public void onClick(View arg0) 
		{
			Button btn = (Button)arg0;
			switch(btn.getId())
			{
			case R.id.btnForward:
				//textMessage.setText("Forward");
				sendCmd("f");
				break;
			case R.id.btnBackward:
				sendCmd("b");
				break;
			case R.id.btnLeft:
				sendCmd("l");
				break;
			case R.id.btnRight:
				sendCmd("r");
				break;
			case R.id.btnStop:
				sendCmd("s");
				break;
			case R.id.btnLogin:
			{
				String str = "";
				try {
				
					str = getPublicTimeline(Weibo.getInstance());
					try {
						JSONObject json = new JSONObject(str);
						
						JSONArray jsonArray = json.getJSONArray("statuses");					
						 for (int i = 0; i < jsonArray.length(); i++)                 
	                        {                    
	                            JSONObject item=jsonArray.getJSONObject(i);                   
	                            String idString=item.getString("id");                     
	                            String textString=item.getString("text");
	                            since_id = idString;
	                            if(textString.length() == 1)
	                            {
	                            	sendCmd(textString);
	                            }
	                        }
						
						
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				} catch (MalformedURLException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				} catch (WeiboException e) {
					e.printStackTrace();
				}
				textMessage.setText(str);
			}
				break;
			
			}
		}
    	
    };
 
    public void sendCmd(String message){
        try {
              outStream = btSocket.getOutputStream();
             } catch (IOException e) {
                e.printStackTrace();
             }
             byte[] msgBuffer;
             msgBuffer = message.getBytes();
             try {
              outStream.write(msgBuffer);
             } catch (IOException e) {
                    e.printStackTrace();
             }
             byte[]msgReturn = new byte[100];
             try{
            	inStream = btSocket.getInputStream();
             	inStream.read(msgReturn,0,100);
             	
             	textMessage.setText(new String(msgReturn,0,100));
             }
             catch(IOException e1){
            	 e1.printStackTrace();
             }
       }
    
    class AuthDialogListener implements WeiboDialogListener {

		@Override
		public void onComplete(Bundle values) {
			
			String token = values.getString("access_token");			
			String expires_in = values.getString("expires_in");
			String uid  = values.getString("uid");
			
			weibo_user_id = uid;
			
			AccessToken accessToken = new AccessToken(token, CONSUMER_SECRET);
			accessToken.setExpiresIn(expires_in);
			Weibo.getInstance().setAccessToken(accessToken);
	
			iLogin = 1;
//			textMessage.setText(values.toString());
//			Toast.makeText(getApplicationContext(),"uid :"+weibo_user_id+"\n access_token : " + token + "\n expires_in: "
//					+ expires_in, Toast.LENGTH_LONG).show();
	
		}
		
		@Override
		public void onError(DialogError e) {
			Toast.makeText(getApplicationContext(),
					"11Auth error : " + e.getMessage(), Toast.LENGTH_LONG).show();
		}

		@Override
		public void onCancel() {
			Toast.makeText(getApplicationContext(), "Auth cancel",
					Toast.LENGTH_LONG).show();
		}

		@Override
		public void onWeiboException(WeiboException e) {
			Toast.makeText(getApplicationContext(),
					"33Auth exception : " + e.getMessage(), Toast.LENGTH_LONG)
					.show();
		}
	}
    
    private void share2weibo(String content, String picPath) throws WeiboException {
        Weibo weibo = Weibo.getInstance();
        weibo.share2weibo(this, weibo.getAccessToken().getToken(), mWeibo.getAccessToken()
                .getSecret(), content, picPath);
    }
    
    private String getPublicTimeline(Weibo weibo) throws MalformedURLException, IOException,
            WeiboException {
        String url = Weibo.SERVER + "statuses/user_timeline.json";
        WeiboParameters bundle = new WeiboParameters();
    
        //请求某用户发布的微博:参数列表         
        /*access_token
        /*uid
        /*screen_name
        /*count
        /*page
        /*since_id :获取id号大于此的微博,即晚于此条微博的微博
        */ 
        bundle.add("access_token", weibo.getAccessToken().getToken());
        bundle.add("uid", weibo_user_id);
        bundle.add("screen_name", "勇敢的轮子儿");
        bundle.add("count", "1");
        bundle.add("since_id", since_id);
 
        //Toast.makeText(getApplicationContext(), weibo.getAccessToken().getToken(), Toast.LENGTH_LONG).show();
        //textMessage.setText(Weibo.getInstance().getAccessToken().toString());
        String rlt = mWeibo.request(JustVideo.this, url, bundle, "GET", mWeibo.getAccessToken());
        //textMessage.setText("rlt:"+rlt);
        return rlt;
    }

	private String getCommentCommand(Weibo weibo) 
		throws MalformedURLException, IOException,WeiboException 
		{
			String url = Weibo.SERVER + "comments/show.json";
			WeiboParameters bundle = new WeiboParameters();
	
			//请求某条微博的评论:参数列表         
			/*access_token
			/*uid
			/*screen_name
			/*count
			/*page
			/*since_id :获取id号大于此的微博,即晚于此条微博的微博
			*/ 
			bundle.add("access_token", weibo.getAccessToken().getToken());
			bundle.add("id", weibo_id);
			//bundle.add("screen_name", "勇敢的轮子儿");
			bundle.add("count", "1");
			bundle.add("since_id", since_id);
			
			String rlt = mWeibo.request(JustVideo.this, url, bundle, "GET", mWeibo.getAccessToken());
			//textMessage.setText("rlt:"+rlt);
			
			return rlt;
	}

	    
    
    private String upload(Weibo weibo, String source, String file, String status, String lon,
            String lat) throws WeiboException {
        WeiboParameters bundle = new WeiboParameters();
        bundle.add("source", source);
        bundle.add("pic", file);
        bundle.add("status", status);
        if (!TextUtils.isEmpty(lon)) {
            bundle.add("lon", lon);
        }
        if (!TextUtils.isEmpty(lat)) {
            bundle.add("lat", lat);
        }
        String rlt = "";
        String url = Weibo.SERVER + "statuses/upload.json";
        try {
            rlt = weibo
                    .request(this, url, bundle, Utility.HTTPMETHOD_POST, weibo.getAccessToken());
        } catch (WeiboException e) {
            throw new WeiboException(e);
        }
        return rlt;
    }

    private String ActionFromWeibo()
    {
    	String str = "";
		try {
		
			str = getPublicTimeline(Weibo.getInstance());
			try {
				JSONObject json = new JSONObject(str);
				
				JSONArray jsonArray = json.getJSONArray("statuses");					
				 for (int i = 0; i < jsonArray.length(); i++)                 
                    {                    
                        JSONObject item=jsonArray.getJSONObject(i);                   
                        String idString=item.getString("id");                     
                        String textString=item.getString("text");
                        since_id = idString;
                        if(textString.length() == 1)
                        {
                        	sendCmd(textString);
                        	textMessage.setText("执行微博命令 :"+textString);
                        	return textString;
                        }
                    }
			} catch (JSONException e) {
				e.printStackTrace();
			}
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (WeiboException e) {
			e.printStackTrace();
		}
		return "";
	}
    
    private String ActionFromComments(String str_weibo_id)
    {
    	String str = "";
		try {
		
			str = getCommentCommand(Weibo.getInstance());
			try {
				JSONObject json = new JSONObject(str);
				
				JSONArray jsonArray = json.getJSONArray("comments");					
				 for (int i = 0; i < jsonArray.length(); i++)                 
                    {                    
                        JSONObject item=jsonArray.getJSONObject(i);                   
                        String idString=item.getString("id");                     
                        String textString=item.getString("text");
                        since_id = idString;
                        if(textString.length() == 1)
                        {
                        	sendCmd(textString);
                        	textMessage.setText("执行微博命令 :"+textString);
                        	return textString;
                        }
                    }
			} catch (JSONException e) {
				e.printStackTrace();
			}
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (WeiboException e) {
			e.printStackTrace();
		}
		return "";
	}
}